package com.eatme.core.trie;

import java.util.HashMap;
import java.util.TreeMap;

public class TrieV2 {

    private class Node{

        public boolean isWord;
        public Node[] next;  // 使用数组

        public Node(boolean isWord){
            this.isWord = isWord;
            next = new Node[26]; // 只 new 26 个空间
        }

        public Node(){
            this(false);
        }
    }

    private Node root;
    private int size;

    private TrieV2() {
        root = new Node();
        size = 0;
    }

    // 获得Trie中存储的单词数量
    public int getSize() {
        return size;
    }

    // 向Trie中添加一个新的单词word
    public void add(String word) {
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (cur.next[c]==null)
                cur.next[c]=new Node();
            cur = cur.next[c];
        }
        if (!cur.isWord) {
            cur.isWord =true;
            size++;
        }
    }

    // 查看单词word是否在Trie中
    public boolean contains(String word) {
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c =word.charAt(i);
            if (cur.next[c]==null)
                return false;
            cur = cur.next[c];
        }
        return cur.isWord;
    }

    // 查询是否在Trie 中有单词以prefix为前缀
    public boolean isPrefix(String prefix) {
        Node cur = root;
        for (int i = 0; i < prefix.length(); i++) {
            char c =prefix.charAt(i);
            if (cur.next[c]==null)
                return false;
            cur = cur.next[c];
        }
        return true;
    }

    public static void main(String[] args) {

    }




}
